package com.lancoo.answer.manager;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.ImgAnswerCallBackBean;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.IndexBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.ui.paper.PaperFragment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import kotlin.Triple;

/**
 * Created by pengmi on 2021/11/30 14:47
 * Description:
 */
public class TaskManager {
    private String tag;

    //作答计时统计
    private Map<String,Long> topicQuesAnswerTimeMap=new HashMap<>();
    private Disposable timerDisPosable;

    /**
     * 加载整份试题
     * @param manager fragmentManager
     * @param taskControlBean 参数控制器
     * @param kindBeanListk  试题结构List
     * @param frameLayoutID frameLayoutID
     */
    public void loadTaskFragment(FragmentManager manager,
                                 TaskControlBean taskControlBean,
                                 List<? extends Type> kindBeanListk, int frameLayoutID){
        tag = UUID.randomUUID().toString();
//        taskControlBean.setOpenZuobiAnswer(true);
//        taskControlBean.setTaskState(TaskState.TRAINING);
        ConstantBean.Companion.setTaskControlBean(taskControlBean);
        ConstantBean.Companion.setSkipToAimIndexBean(null);
        ExamViewBean bean=new ExamViewBean();
        bean.setTypeList(kindBeanListk);
        ConstantBean.Companion.setConstantExamBean(bean);
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        PaperFragment fragment=new PaperFragment();
        fragmentTransaction.replace(frameLayoutID,fragment, tag);
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 开启答题卡
     * @param manager fragmentManager
     */
    public void showPaperAnswerSheetDialog(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).showAnswerSheetDialog();
        }
    }

    /**
     * 关闭答题卡
     * @param manager fragmentManager
     *
     */
    public void closePaperAnswerSheetDialog(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).closeAnswerSheetDialog();
        }
    }

    /**
     * 关闭所有音频播放
     * @param manager fragmentManager
     */
    public void closeAllPaperAudioPlay(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).closeAllAudioPlay();
        }
    }

    /**
     * 获取当前Type,Ques,Child下标
     * @param manager fragmentManager
     */
    public Triple<Integer,Integer,Integer> getCurrentIndex(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            return ((PaperFragment) fragmentByTag).getCurrentIndex();
        }
        return new Triple<>(0,0,0);
    }


    /**
     * 获取当前Type,Ques,Child,ItemIndex下标
     * @param manager fragmentManager
     */
    public IndexBean getAllRealIndex(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            return ((PaperFragment) fragmentByTag).getAllRealIndex();
        }
        return new IndexBean();
    }

    /**
     * 外部跳转指定fragment
     * @param manager fragmentManager
     * @param typeIndex 题型下标
     * @param quesIndex 大题下标
     * @param chlidIndex 小题下标
     * @param itemIndex 答题点下标
     */
    public void skipToAimFragment(FragmentManager manager,int typeIndex,int quesIndex,
                                  int chlidIndex,int itemIndex){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).skipToAimFragment(typeIndex,quesIndex,chlidIndex,itemIndex,false,false);
        }
    }

    /**
     * 跳转指定的导语界面
     * @param manager fragmentManager
     * @param typeIndex 题型下标
     */
    public void skipToAimLeardFragment(FragmentManager manager,int typeIndex){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).skipToAimFragment(typeIndex,0,0,0,true,false);
        }
    }

    /**
     * 外部调用大题音频播放（过关训练专用）
     * @param manager fragmentManager
     */
    public void autoPlayAudio(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).autoPlayAudio();
        }
    }


    /**
     * 更新当前大题的作答倒计时 （考试专用）
     * @param typeIndex 题型下标
     * @param quesIndex 大题下标
     * @param chlidIndex 小题下标
     * @param countdown 倒计时 秒
     * @param isShow 是否显示
     */
    public void updateChildAnswerCountdown(FragmentManager manager,int typeIndex,int quesIndex,
                                           int chlidIndex,int countdown,boolean isShow){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).updateChildAnswerCountdown(typeIndex,quesIndex,chlidIndex,countdown,isShow);
        }
    }

    /**
     * 更新播放样式状态（考试专用）
     * @param typeIndex 题型下标
     * @param quesIndex 大题下标
     * @param isPlaying 是否处于播放状态
     */
    public void updateQuesAudioPlayState(FragmentManager manager,int typeIndex,int quesIndex,boolean isPlaying){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).updateQuesAudioPlayState(typeIndex,quesIndex,isPlaying);
        }
    }

    /**
     * 关闭音频作答进程（考试专用）
     * @param manager fragmentManager
     */
    public void closeAudioAnswerProcess(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).closeAudioAnswerProcess();
        }
    }

    /**
     * 开始作答计时
     */
    public void startTimer(FragmentManager manager){
        pauseTimer();
        timerDisPosable = Observable.interval(20, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    Triple<Integer, Integer, Integer> currentIndex = getCurrentIndex(manager);
                    Integer typeIntex = currentIndex.getFirst();
                    Integer quesIndex = currentIndex.getSecond();
                    String key=typeIntex+""+quesIndex;
                    try{
                        Long longTime = topicQuesAnswerTimeMap.get(key);
                        if(longTime!=null){
                            topicQuesAnswerTimeMap.put(key,longTime+20);
                        }else{
                            topicQuesAnswerTimeMap.put(key,20l);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });

    }

    /**
     * 暂停作答计时
     */
    public void pauseTimer(){
        if(timerDisPosable!=null){
            timerDisPosable.dispose();
        }
    }

    /**
     * 清空作答时长
     */
    public void clearAnswerTime(){
        topicQuesAnswerTimeMap.clear();
    }

    /**
     * 获取作答时长
     * @return
     */
    public Map<String,Long> getAnswerTimeMap(){
        return topicQuesAnswerTimeMap;
    }


    /**
     * 更改字体大小
     */
    public void adjustFontSize(FragmentManager manager){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).adjustFontSize();
        }
    }

    /**
     * 标记不确定小题
     */
    public void markQuestion(FragmentManager manager){
        Fragment fragment=manager.findFragmentByTag(tag);
        if(fragment instanceof PaperFragment){
            ((PaperFragment) fragment).markQuestion();
        }
    }
    /**
     * 图片外部作答回调
     * @param manager fragmentManager
     */
    public void updateImgAnswerCallBack(FragmentManager manager, ImgAnswerCallBackBean bean){
        Fragment fragmentByTag = manager.findFragmentByTag(tag);
        if(fragmentByTag instanceof PaperFragment){
            ((PaperFragment) fragmentByTag).updateImgAnswerCallBack(bean);
        }
    }


}
